<template>
    <section class="content-wrapper">
        <a class="back" href="javascript:void(0)" @click="back"></a>
        <el-row :gutter="20">
            <el-col :span="24" class="cms-form-box">

                <el-row>
                    <el-col>
                        <el-form :inline="false" :model="form" ref="form" :rules="rules" v-loading="loading" label-width="150px">


                            <el-row :gutter="20">
                                <el-col :span="10">
                                    <el-form-item label="业务编码">
                                        <el-input v-model="form.keyCode" placeholder="业务唯一编码，针对业务查询"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="10">
                                    <el-form-item label="图文标题">
                                        <el-input
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 4}"
                                                placeholder="变量格式：{username}==>{username}邀请你注册为会员"
                                                v-model="form.title">
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="10">
                                    <el-form-item label="图片链接">
                                        <el-input v-model="form.picUrl" placeholder="图片链接，支持JPG、PNG格式，较好的效果为大图360*200，小图200*200"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <file-upload
                                            class="select-file-bto lh-38"
                                            :post-action="uploadAction"
                                            :extensions="extensions"
                                            :accept="accept"
                                            :multiple="true"
                                            :size="size || 0"
                                            :thread="thread < 1 ? 1 : (thread > 5 ? 5 : thread)"
                                            :headers="headers"
                                            :drop="true"
                                            :drop-directory="true"
                                            v-model="files"
                                            @input-filter="inputFilter"
                                            @input-file="inputFile"
                                            ref="upload">
                                        上传文件
                                    </file-upload>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20" v-if="files.length === 0 && form.picUrl">
                                <el-col :span="10">
                                    <el-form-item>
                                        <img :src="form.picUrl" style="max-width: 320px; max-height:200px;" />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20" v-if="files.length > 0">
                                <el-col :span="10">
                                    <el-form-item>
                                        <div class="img-preview">
                                            <div class="img-box">
                                                <img v-if="files" :src="files[0].thumb" style="max-width: 320px; max-height:200px;" />
                                            </div>
                                            <div class="progress">
                                                <el-tag
                                                        closable
                                                        @close="removeImg"
                                                        type="primary" size="small"
                                                > {{files[0].name}} </el-tag>
                                                <span v-if="files[0].error" style="color: #FA5555">上传失败</span>
                                                <span v-else-if="files[0].success" style="color: #67C23A">成功</span>
                                                <span v-else-if="files[0].active" style="color: #409EFF">上传中</span>
                                            </div>
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="10">
                                    <el-form-item label="图文URL">
                                        <el-input
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 4}"
                                                placeholder="变量格式：{code}==>http://www.xx.net/article/id={code}"
                                                v-model="form.url">
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="10">
                                    <el-form-item label="图文描述">
                                        <el-input
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 4}"
                                                placeholder="请输入内容"
                                                v-model="form.description">
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="10">
                                    <el-form-item label="业务备注">
                                        <el-input
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 4}"
                                                placeholder="业务备注"
                                                v-model="form.remarks">
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="15">
                                    <el-form-item label="图文内容" class="editor-form-item">
                                        <vue-editor v-model="form.content"></vue-editor>
                                        <!--<u-editor :id="editorId" :defaultMsg="defaultMsg" :config="config" ref="ue"></u-editor>-->
                                    </el-form-item>
                                </el-col>
                            </el-row>


                            <el-form-item>
                                <el-button v-if="params.articleId" type="primary" @click="update">编 辑</el-button>
                                <el-button v-else type="primary" @click="create">提 交</el-button>
                                <el-button @click="back">取 消</el-button>
                            </el-form-item>

                        </el-form>
                    </el-col>
                </el-row>

            </el-col>

        </el-row>

    </section>
</template>

<script>
    import { created, updated, selectTree, getParents, selectOne } from '@/api/weixin/article'
    import { VueEditor, Quill } from 'vue2-editor'
    import FileUpload from 'vue-upload-component'
    import { deleted, deleteByViewUrl, uploadAction } from '@/api/system/oss'

    export default {
        components: {VueEditor, FileUpload},
        name: 'WeixinMenuForm',
        data() {
            return {
                /**
                 * articleId
                 */
                params: this.$route.query,
                loading: false,
                form: {
                    title: null,
                    name: null,
                    description: null,
                    content: null,
                    picUrl: null,
                    url: null,
                    status: 1,
                    keyCode: null,
                    remarks: null,
                    articleTxt: {
                        txt: ''
                    }
                },
                rules: {},
                editorId: 'ue',
                defaultMsg: '',
                config: {
                    initialFrameWidth: null,
                    initialFrameHeight: 350
                },
                files: [],
                uploadAuto: true,
                uploadAction: uploadAction,
                autoCompress: 1024 * 1024 * 10,
                size: 1024 * 1024 * 10,
                thread: 3,
                accept: 'image/png,image/gif,image/jpeg,image/webp',
                extensions: 'gif,jpg,jpeg,png,webp',
                headers: {
                    'X-Token': 'xxxx'
                },
                uploadForm: {
                    ossName: 'qiniuyun',
                    bucketName: 'weixin',
                    prefixName: null,
                    remark: '微信图文'
                }
            }
        },
        created() {
            if(this.params.articleId) {
                selectOne(this.params.articleId).then(response => {
                    this.form = Object.assign({}, response.data)
                    this.form.content = this.form.articleTxt.txt
                })
            }
        },
        methods: {
            back() {
                this.$router.go(-1)
            },

            removeImg() {
                deleteByViewUrl({"viewUrl": this.form.picUrl}).then(() => {})
                this.files = []
                this.form.picUrl = null
            },
            create() {//添加数据
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        this.form.articleTxt.txt = this.form.content; // 调用子组件方法

                        created(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.$router.go(-1)
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })
                    }
                })
            },
            update() {//修改数据
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        this.form.articleTxt.txt = this.form.content; // 调用子组件方法

                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.$router.go(-1)
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })
                    }
                })
            },
            inputFilter(newFile, oldFile, prevent) {
                if (newFile && !oldFile) {
                    // 添加文件前
                    // 过滤系统文件 和隐藏文件
                    if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
                        return prevent()
                    }
                    // 过滤 php html js 文件
                    if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
                        return prevent()
                    }

                    // 自动压缩
                    if (newFile.file && newFile.type.substr(0, 6) === 'image/' && this.autoCompress > 0 && this.autoCompress < newFile.size) {
                        newFile.error = 'compressing'
                        const imageCompressor = new ImageCompressor(null, {
                            convertSize: Infinity,
                            maxWidth: 320,
                            maxHeight: 200,
                        })
                        imageCompressor.compress(newFile.file)
                            .then((file) => {
                                this.$refs.upload.update(newFile, { error: '', file, size: file.size, type: file.type })
                            })
                            .catch((err) => {
                                this.$refs.upload.update(newFile, { error: err.message || 'compress' })
                            })
                    }

                    if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
                        // 创建 blob 字段
                        newFile.blob = ''
                        let URL = window.URL || window.webkitURL
                        if (URL && URL.createObjectURL) {
                            newFile.blob = URL.createObjectURL(newFile.file)
                        }
                        // 缩略图
                        newFile.thumb = ''
                        if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
                            newFile.thumb = newFile.blob
                        }
                    }
                }
            },
            inputFile(newFile, oldFile) {
                if (newFile && !oldFile) {
                    // 添加文件
                }

                if (newFile && oldFile) {
                    // 更新文件

                    // 开始上传
                    if (newFile.active && !oldFile.active) {
                        // beforeSend
                        //设置每个文件携带的参数
                        newFile.data = Object.assign({}, this.uploadForm)

                        // 限定最小字节
                        if (newFile.size >= 0 && this.minSize > 0 && newFile.size < this.minSize) {
                            this.$refs.upload.update(newFile, { error: 'size' })
                        }
                    }
                    // 上传进度
                    if (newFile.progress !== oldFile.progress) {
                        //console.log('progress', newFile.progress, newFile)
                    }
                    // 上传错误
                    if (newFile.error !== oldFile.error) {
                        //console.log('error', newFile.error, newFile)
                    }
                    // 上传成功
                    if (newFile.success !== oldFile.success) {
                        //console.log('success', newFile.success, newFile)
                        this.form.picUrl = newFile.response.url
                    }
                }

                if (!newFile && oldFile) {
                    // 删除文件
                    // 自动删除 服务器上的文件
                    if (oldFile.success && oldFile.response.id) {
                        // $.ajax({
                        //   type: 'DELETE',
                        //   url: '/file/delete?id=' + oldFile.response.id,
                        // });
                    }
                }

                // 自动上传
                if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
                    if (this.uploadAuto && !this.$refs.upload.active) {
                        this.$refs.upload.active = true
                    }
                }
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>

</style>